import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Login from '@/views/login'
import Likede from '@/views/likede'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/likede',
    children: [
      {
        path: '/likede',
        component: Likede
      }
    ]
  },
  {
    path: '/login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login']
const token = getToken()
router.beforeEach((to, from, next) => {
  // to表示去哪  from表示从哪个路由来的 next是一个函数
  // 只有调用next,才会正常放行,next(path),可以跳到指定路径
  // console.log(to, from)
  if (token) {
    // 如果有token就直接放行
    next()
  } else {
    // 想去的页面是否包含在白名单中
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 否则去登录页面
      next('/login')
    }
  }
})
export default router
